import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/token.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';

class MinePage extends StatefulWidget {
  MinePage({super.key, required this.currentIndex});
  //定义当前的下标
  int currentIndex = 1;
  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "images/visitor_profile_icon@2x.png",
    }
  ];

  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    //发请求,拿数据
    //如果希望 没有等于可以看到我的页面  就使用下面的代码
    // if (widget.currentIndex == 1 && TokenManager().getToken() != null) {
    //   //拿到用户数据
    //   getUserInfo();
    // }

    //如果希望没有登录的话  ,直接跳转到登录页面  就使用下面的代码
    if (widget.currentIndex == 1) {
      getUserInfo();
    }
  }

//个人数据状态变量
  Map info = {"avatar": '', 'id': 0, 'nickName': ''};
  //获取用户数据
  getUserInfo() async {
    final res = await http.get('/userInfo');
    //print(res['data']);
    setState(() {
      info = res['data'];
    });
  }

  @override
  void initState() {
    super.initState();

    //在这里注册事件总线
    eventBus.on<RefreshEvent>().listen((event) {
      getUserInfo();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: const Text('我的', style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 个人信息
          Container(
              padding: const EdgeInsets.all(10),
              child: GestureDetector(
                  onTap: () {
                    //传递参数
                    Navigator.pushNamed(context, '/profile', arguments: info);
                    //测试
                    // TokenManager().saveToken('123456'); //保存token
                    // print(TokenManager().getToken());      //获取Token
                    // TokenManager().removeToken(); //清除token

                    //判断是否登录  如果登录的话就去个人中心，否则去登录页面
                    //这个逻辑没有问题,但是如果有多个地方需要登录的话,需要写多次会麻烦
                    //可以在main 里面进行路由拦截
                    // if (TokenManager().getToken() != null) {
                    //   Navigator.pushNamed(context, '/profile');
                    // } else {
                    //   Navigator.pushNamed(context, '/login');
                    // }
                  },
                  child: Row(children: [
                    Row(children: [
                      ClipRRect(
                          borderRadius: BorderRadius.circular(50.0),
                          child: info['id'] == 0
                              ? Image.asset('images/avatar_1.jpg',
                                  width: 50, height: 50)
                              : Image.network(info['avatar'],
                                  width: 50, height: 50)),
                      const SizedBox(width: 10),
                      Text('${info['id'] == 0 ? '未登录' : info['nickName']}',
                          style: const TextStyle(
                              fontSize: 16, color: Colors.white))
                    ]),
                    const Spacer(),
                    const Row(children: [
                      Text(
                        '去完善信息',
                        style: TextStyle(color: Colors.white),
                      ),
                      Icon(
                        Icons.arrow_forward_ios,
                        color: Colors.white,
                        size: 13,
                      )
                    ])
                  ]))),
          Container(
              padding: const EdgeInsets.all(15),
              margin: const EdgeInsets.only(
                  top: 20, left: 10, right: 10, bottom: 20),
              decoration: BoxDecoration(
                  color: Colors.white, borderRadius: BorderRadius.circular(10)),
              child: Column(
                  children: menuList.map((item) {
                return SizedBox(
                    height: 50,
                    child: Row(children: [
                      Row(
                        children: [
                          Image.asset(
                            item['icon'],
                            width: 20,
                            height: 20,
                          ),
                          const SizedBox(
                            width: 10,
                          ),
                          Text(
                            item['title'],
                            style: const TextStyle(fontSize: 16),
                          )
                        ],
                      ),
                      const Spacer(),
                      const Icon(
                        Icons.arrow_forward_ios,
                        size: 12,
                        color: Colors.grey,
                      )
                    ]));
              }).toList()))
        ],
      ),
    );
  }
}
